package org.cy.evolution.net.http.exception;

import android.content.Context;
import android.util.MalformedJsonException;

import com.alibaba.fastjson.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;

import retrofit2.HttpException;


public class ExceptionHandler {

    public static ApiException handle(Throwable e) {
        ApiException aex;
        HttpStatus status = HttpStatus.UNEXPECTED_ERROR;
        if (e instanceof HttpException) {
            HttpException httpEx = (HttpException) e;
            status = HttpStatus.valueOfByCode(httpEx.code());
        } else if (e instanceof JSONException ||
                e instanceof ParseException ||
                e instanceof MalformedJsonException) {
            status = HttpStatus.RESPONSE_PARSE_ERROR;
        } else if (e instanceof UnknownHostException ||
                e instanceof ConnectException) {
            status = HttpStatus.NOT_CONNECT;
        } else if (e instanceof SocketTimeoutException) {
            status = HttpStatus.CONNECTION_TIMEOUT;
        }
        aex = new ApiException(e, status.getCode(), status.getMsg());
        return aex;
    }
}
